package com.hmdp.utils;

import com.hmdp.dto.UserDTO;
import com.hmdp.entity.User;
import net.sf.jsqlparser.expression.operators.relational.Between;
import org.springframework.beans.BeanUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Yandel
 * @date 2025/6/14 下午9:37
 * @description: 具体的登录拦截器
 */
public class LoginInterceptor  implements HandlerInterceptor {

    /**
     * 负责在请求前进行登录状态校验
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/*        //1、获取session
        HttpSession  session = request.getSession();
        //2、获取session中的用户 将User转成UserDTO
        UserDTO userEntity = (UserDTO) session.getAttribute("user");

        //3、判断用户是否存在
        if (userEntity == null) {
            //4、不存在，拦截，返回401
            response.setStatus(401);
            return false;
        }
        //5、存在，保存用户信息到ThreadLocal
        UserHolder.saveUser(userEntity);
        //6、放行
        return true;*/

        //1、判断是否需要拦截 （ThreadLocal中保存的user是否为空）
        if (UserHolder.getUser() == null){
            //没有需要拦截   设置状态码
            response.setStatus(401);

            //如果没有，直接拦截
            return false;
        }
        //2、有用户，放行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
